<?php

namespace app\api\lists\talent;

use app\admin\model\User;
use app\api\lists\BaseApiDataLists;
use app\common\enum\StatusEnum;
use app\common\enum\YesNoEnum;

/**
 * 文章列表
 * Class TalentLists
 * @package app\api\lists\article
 */
class TalentLists extends BaseApiDataLists
{

    /**
     * @notes 自定查询条件
     * @return array
     * @author 段誉
     * @date 2022/10/25 16:53
     */
    public function queryWhere()
    {
        $where[] = ['u.status', '=', YesNoEnum::YES];
        $where[] = ['u.user_type', '=', 2];
        $where[] = ['h.approve_status', '=', StatusEnum::APPROVED];
        if (!empty($this->params['keyword'])) {
            $where[] = ['h.real_name', 'like', '%' . $this->params['keyword'] . '%'];
        }
        return $where;
    }


    /**
     * @notes 获取文章列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function lists(): array
    {
        $orderRaw = 'h.real_name desc';
        $sortType = $this->params['sort'] ?? 'default';
        // 最新排序
        if ($sortType == 'help') {
            $orderRaw = 'u.likes desc';
        }

        $result = (new User())->alias('u')->join('helper_info h', 'u.id = h.user_id')->join('system_village v','v.id=h.village_id')
            ->field('u.id,u.nickname,u.avatar,u.likes,h.real_name,h.id as helper_id,h.phone,h.village_id,v.name as village_name,h.photo')
            ->where($this->queryWhere())
            ->orderRaw($orderRaw)
            ->limit($this->limitOffset, $this->limitLength)
            ->select()->toArray();
        foreach ($result as &$item) {
            $item['phone'] = substr_replace($item['phone'], '****', 3, 4);
            if($item['photo'] == ''){
                $item['photo'] = '/static/images/default_avatar.png';
            }
        }
        return $result;
    }


    /**
     * @notes 获取文章数量
     * @return int
     */
    public function count(): int
    {
        return (new User())->alias('u')->join('helper_info h', 'u.id = h.user_id')
            ->where($this->queryWhere())
            ->count();
    }
}